package com.example.seh.square;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.StrictMode;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.example.seh.R;
import com.example.seh.util.ImgUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

public class SquareAdapter extends BaseAdapter {

    private Context context;
    private List<Post> lists;
    private int item;
    private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
    private static String timeStr = null;
    private Bitmap bitmap;
    private String[] pics;
//    private Handler handler = new Handler(Looper.myLooper()){
//        @Override
//        public void handleMessage(@NonNull Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what){
//                case 0:
//                    bitmap = (Bitmap) msg.obj;
//                    break;
//                case 1:
//                    ViewHolder viewHolder = (ViewHolder) msg.obj;
//                    viewHolder.avatarId.setImageBitmap(bitmap);
//                    break;
//                case 2:
//                    bitmap = (Bitmap) msg.obj;
//                    break;
//                case 3:
//                    ViewHolder viewHolder1 = (ViewHolder) msg.obj;
//                    viewHolder1.pic1.setImageBitmap(bitmap);
//                    break;
//                case 4:
//                    bitmap = (Bitmap) msg.obj;
//                    break;
//                case 5:
//                    ViewHolder viewHolder2 = (ViewHolder) msg.obj;
//                    viewHolder2.pic2.setImageBitmap(bitmap);
//                    break;
//            }
//        }
//    };

    public SquareAdapter(Context context, List<Post> lists, int item) {
        this.context = context;
        this.lists = lists;
        this.item = item;
    }
    @Override
    public int getCount() {
        if (lists != null) {
            return lists.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        if (lists != null) {
            return lists.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(item, null);
            viewHolder = new ViewHolder();
            viewHolder.avatarId = convertView.findViewById(R.id.iv_avatar);
            viewHolder.userName = convertView.findViewById(R.id.tv_name);
            viewHolder.time = convertView.findViewById(R.id.tv_introduce);
            viewHolder.title = convertView.findViewById(R.id.tv_title);
            viewHolder.content = convertView.findViewById(R.id.tv_content);
            viewHolder.pic1 = convertView.findViewById(R.id.iv_pic1);
            viewHolder.pic2 = convertView.findViewById(R.id.iv_pic2);
            viewHolder.replyPic = convertView.findViewById(R.id.iv_reply);
            viewHolder.reply = convertView.findViewById(R.id.tv_reply);
            convertView.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.userName.setText(lists.get(position).getUserDTO().getUsername());


//        LocalDateTime now = LocalDateTime.now();
//        System.out.println(now);
//        String pattern = "yyyy-MM-dd HH:mm:ss.S";
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
//        LocalDateTime givenTime = LocalDateTime.parse(lists.get(position).getCreateTime(), formatter);
//        Duration duration = Duration.between(givenTime,now);
//        Period period = Period.between(givenTime.toLocalDate(), now.toLocalDate());
//        // 判断是几小时前还是几天前
//        if (period.getYears() > 0) {
//            viewHolder.time.setText(period.getYears() + "年前");
//        } else if(period.getMonths() > 0) {
//            viewHolder.time.setText(period.getMonths() + "月前");
//        } else if (period.getDays() > 0){
//            viewHolder.time.setText(period.getDays() + "天前");
//        } else if (duration.toHours() > 0){
//            viewHolder.time.setText(duration.toHours() + "小时前");
//        } else {
//            viewHolder.time.setText(duration.toMinutes() + "分钟前");
//        }

        try {

            getTime(dateFormat.parse(lists.get(position).getCreateTime()).getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        viewHolder.time.setText(timeStr);
        viewHolder.title.setText(lists.get(position).getTitle());
        viewHolder.content.setText(lists.get(position).getContent());
        int replyNum = lists.get(position).getReply();
        if (replyNum == 0){
            viewHolder.reply.setText("回复");
        }else {
            viewHolder.reply.setText(lists.get(position).getReply()+"");
        }

//        StrictMode.setThreadPolicy(new
//                StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
//        StrictMode.setVmPolicy(
//                new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());


        if (!"".equals(lists.get(position).getUserDTO().getPic())){
            Glide.with(context)
                    .load(lists.get(position).getUserDTO().getPic())
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(viewHolder.avatarId);
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    Bitmap bitmap = stringToBitmap(lists.get(position).getUserDTO().getPic());
//
//                    Message message = new Message();
//                    message.what = 0;
//                    message.obj = bitmap;
//                    handler.sendMessage(message);
//
//                    Message message1 = new Message();
//                    message1.what = 1;
//                    message1.obj = viewHolder;
//                    handler.sendMessage(message1);
//                }
//            }).start();
            //viewHolder.avatarId.setImageBitmap(stringToBitmap(lists.get(position).getUserDTO().getPic()));
        }else {
            viewHolder.avatarId.setImageResource(R.mipmap.default_avatar);
        }

        if (lists.get(position).getPicPath() != null){
            pics = lists.get(position).getPicPath().split(";");
            if (!pics[0].isEmpty()) {
                viewHolder.pic1.setVisibility(View.VISIBLE);
                Glide.with(context)
                        .load(pics[0])
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .dontAnimate()
                        .listener(new RequestListener<Drawable>() {
                            @Override
                            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                if (target instanceof ImageView) {
                                    ((ImageView) target).setTag(pics[0]);  // 绑定加载请求与视图
                                }
                                return false;
                            }
                        })
                        .into(viewHolder.pic1);
            } else {
                Glide.with(context)
                        .clear(viewHolder.pic1);  // 清除之前的加载请求，避免复用时显示错误的图片
                viewHolder.pic1.setImageDrawable(null);  // 或者设置默认占位图像

            }

            if (pics.length >= 2 && !pics[1].isEmpty()){
                viewHolder.pic2.setVisibility(View.VISIBLE);
                Glide.with(context)
                        .load(pics[1])
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .dontAnimate()
                        .listener(new RequestListener<Drawable>() {
                            @Override
                            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                if (target instanceof ImageView) {
                                    ((ImageView) target).setTag(pics[1]);  // 绑定加载请求与视图
                                }
                                return false;
                            }
                        })
                        .into(viewHolder.pic2);
            } else {
                Glide.with(context)
                        .clear(viewHolder.pic2);  // 清除之前的加载请求，避免复用时显示错误的图片
                viewHolder.pic2.setImageDrawable(null);  // 或者设置默认占位图像

            }

//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//
//                    if (!pics[0].isEmpty()){
//                        Bitmap bitmap = stringToBitmap(pics[0]);
//                        Message message2 = new Message();
//                        message2.what = 2;
//                        message2.obj = bitmap;
//                        handler.sendMessage(message2);
//
//                        Message message3 = new Message();
//                        message3.what = 3;
//                        message3.obj = viewHolder;
//                        handler.sendMessage(message3);
//                    }else {
//                        ((Activity)context).runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                viewHolder.pic1.setVisibility(View.GONE);
//                            }
//                        });
//                    }
//                    if (pics.length >= 2 && !pics[1].isEmpty()){
//                        Bitmap bitmap = stringToBitmap(pics[1]);
//                        Message message4 = new Message();
//                        message4.what = 4;
//                        message4.obj = bitmap;
//                        handler.sendMessage(message4);
//
//                        Message message5 = new Message();
//                        message5.what = 5;
//                        message5.obj = viewHolder;
//                        handler.sendMessage(message5);
//                    }else {
//                        ((Activity)context).runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                viewHolder.pic2.setVisibility(View.GONE);
//                            }
//                        });
//                    }
//                }
//            }).start();
        }else{
            viewHolder.pic1.setVisibility(View.GONE);
            viewHolder.pic2.setVisibility(View.GONE);
        }
        return convertView;
    }

    class ViewHolder {
        private CircleImageView avatarId;
        private ImageView pic1,pic2,replyPic;
        private TextView userName,time,title,content,reply;
    }
    public Bitmap stringToBitmap(String string) {
        try {
            URL url = new URL(string);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            if (conn.getResponseCode() == 200) {
                InputStream inputStream = conn.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                return ImgUtil.scaleBitmap(bitmap, 0.5f);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 获取评论/回复的时间差
     *
     * @param time
     * @return
     */
    public static String getTime(long time) {

        long nowTime = System.currentTimeMillis();

        int day = (int) ((nowTime - time) / 86400000);
        int hour = (int) ((nowTime - time) / 3600000);
        int minute = (int) ((nowTime - time) / 60000);
        int second = (int) ((nowTime - time) / 1000);
        if (day >= 365) {
            int c = day / 365;
            timeStr = c + "年前";
        } else if (day >= 1) {
            timeStr = day + "天前";
        } else if (hour >= 1) {
            timeStr = hour + "小时前";
        } else if (minute >= 1) {
            timeStr = minute + "分钟前";
        } else if (second > 0) {
            timeStr = second + "秒前";
        } else {
            timeStr = "刚刚";
        }
        return timeStr;
    }


}
